import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Put,
  ParseIntPipe,
  Delete,
} from '@nestjs/common';
import { RolesService } from './roles.service';
import { CommonObjectProps, CommonResponse } from '../typings';
import { responseWrapper } from '../utils';

@Controller('roles')
export class RolesController {
  constructor(private readonly roleService: RolesService) {}

  @Get()
  async roles(): Promise<CommonResponse> {
    try {
      const res = await this.roleService.roles();
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Post()
  async addRole(@Body() role: CommonObjectProps): Promise<CommonResponse> {
    try {
      console.log(role);
      const res = await this.roleService.addRole(role);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get(':id')
  async getPost(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.roleService.getRole(id);
      if (!res) throw new Error('角色不存在');
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Put(':id')
  async update(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() data: CommonObjectProps,
  ): Promise<CommonResponse> {
    try {
      const res = await this.roleService.update(id, data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Delete(':id')
  async delete(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.roleService.delete(id);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }
}
